package com.ln.lnzw.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ln.lnzw.R;
import com.ln.lnzw.adapter.EvaluationAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;
import com.ln.lnzw.bean.EnaluationBean;
import com.ln.lnzw.bean.LoginBean;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.TokenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wuwei on 2018/4/20.
 * 我的评价
 */

public class EvaluationActivity extends BaseActivity {
    private static final int MYLIVE_MODE_CHECK = 0;
    private static final int MYLIVE_MODE_EDIT = 1;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.bianji)
    TextView bianji;
    @BindView(R.id.rv_recyclerview)
    RecyclerView rvRecyclerview;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ll_mycollection_bottom_dialog)
    LinearLayout llMycollectionBottomDialog;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_cancle)
    TextView tvCancle;
    private EvaluationAdapter mAdapter = null;
    private List<EnaluationBean.ResultBean.ListBean> mList = new ArrayList<>();
    private String name;
    private int mEditMode = MYLIVE_MODE_CHECK;
    private boolean isSelectAll = false;
    private boolean editorStatus = false;
    private int index = 0;
    private int requestCode = 0;
    private String userId;
    private String token;
    private int page = 1;
    private int limit = 10;
    private static final String TAG = "EvaluationActivity";
    private int lastSize = 0;
    private int nowSize = 0;
    private int delayMillis = 1000;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluation_suggestion_complain);
        ButterKnife.bind(this);
        setView();
        initData();
        initListener();
    }

    private void initData() {
        userId = activity.spUtils.getString(AppConstant.USER_UID);
        token = activity.spUtils.getString(AppConstant.TOKEN);
        HttpMethods.getInstanceCenter().info.getEvaluation(token,userId,page,limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<EnaluationBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                            addDisposable(d);
                    }

                    @Override
                    public void onNext(EnaluationBean enaluationBean) {
                        if (mList!= null || !mList.isEmpty()){mList.clear();}
                        if (null!= enaluationBean.getResult()&& null != enaluationBean.getResult().getList()){
                            mList.addAll(enaluationBean.getResult().getList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: "+e.toString());
                        dispose();
                    }

                    @Override
                    public void onComplete() {
                        mAdapter.notifyDataSetChanged();
                    }
                });

    }

    private void setView() {
        name = getIntent().getStringExtra("name");
        tvName.setText(name);
        rvRecyclerview.setLayoutManager(new LinearLayoutManager(activity));
        mAdapter = new EvaluationAdapter(R.layout.item_activity_evaluation_suggestion_complain, mList);
        rvRecyclerview.setAdapter(mAdapter);

        ViewGroup.LayoutParams paramsCancle = tvCancle.getLayoutParams();

        paramsCancle.width = ScreenUtils.getScreenWidth()*28/75;
        paramsCancle.height = paramsCancle.width*2/7;
        tvCancle.setLayoutParams(paramsCancle);

        ViewGroup.LayoutParams paramsDelete = tvDelete.getLayoutParams();

        paramsDelete.width = ScreenUtils.getScreenWidth()*28/75;
        paramsDelete.height = paramsDelete.width*2/7;
        tvDelete.setLayoutParams(paramsDelete);

        refreshLayout.setDisableContentWhenRefresh(true);//是否在刷新的时候禁止列表的操作
        refreshLayout.setDisableContentWhenLoading(true);//是否在加载的时候禁止列表的操作
        //设置下拉刷新监听事件
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                downRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                onLoadMoreRequested();
            }
        });

    }

    /**
     * 下拉刷新方法,重置页数重新请求
     */
    private void downRefresh(){
        page = 1;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setNoMoreData(false);
                initData();
                refreshLayout.finishRefresh();
            }
        }, delayMillis);
    }

    private void onLoadMoreRequested(){
        userId = activity.spUtils.getString(AppConstant.USER_UID);
        token = activity.spUtils.getString(AppConstant.TOKEN);
        HttpMethods.getInstanceCenter().info.getEvaluation(token,userId,page+1,limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<EnaluationBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(EnaluationBean enaluationBean) {

                        if (null!= enaluationBean.getResult()&& null != enaluationBean.getResult().getList()){
                            mList.addAll(enaluationBean.getResult().getList());
                            nowSize = mList.size();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: "+e.toString());
                        dispose();
                    }

                    @Override
                    public void onComplete() {
                        if (nowSize>lastSize){
                            mAdapter.setNewData(mList);
                            mAdapter.notifyDataSetChanged();
                        }
                        refreshLayout.finishLoadMore(delayMillis);
                    }
                });
    }

    private void initListener() {
        rvRecyclerview.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (editorStatus) {
                    EnaluationBean.ResultBean.ListBean news = mList.get(position);
                    boolean isSelect = news.isSelect();
                    if (!isSelect) {
//                        index++;
                        news.setSelect(true);
                        if (index == mList.size()) {
                            isSelectAll = true;
//                            selectAll.setText("取消全选");
                        }

                    } else {
                        news.setSelect(false);
//                        index--;
                        isSelectAll = false;
//                        selectAll.setText("全选");
                    }
//                    setBtnBackground(index);
//                    tvSelectNum.setText(String.valueOf(index));
                    mAdapter.notifyDataSetChanged();
                } else {

                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.bianji, R.id.tv_cancle, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bianji:
                updataEditMode();
                break;
            case R.id.tv_cancle:

                break;
            case R.id.tv_delete:

                break;
        }
    }

    private void updataEditMode() {
        mEditMode = mEditMode == MYLIVE_MODE_CHECK ? MYLIVE_MODE_EDIT : MYLIVE_MODE_CHECK;
        if (mEditMode == MYLIVE_MODE_EDIT) {
            bianji.setText("取消");
            llMycollectionBottomDialog.setVisibility(View.VISIBLE);
            editorStatus = true;
        } else {
            index = 0;
            bianji.setText("编辑");
            llMycollectionBottomDialog.setVisibility(View.GONE);
            editorStatus = false;
            clearAll();
            for (int i = 0, j = mAdapter.getData().size(); i < j; i++) {
                mAdapter.getData().get(i).setSelect(false);
            }
        }
        mAdapter.setEditMode(mEditMode);
    }

    private void clearAll() {
//        tvSelectNum.setText(String.valueOf(0));
        isSelectAll = false;
//        selectAll.setText("全选");
//        setBtnBackground(0);
    }
}
